package my.mybatis.common.util;

import java.io.*;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

public class FileMD5Util {
	/**
	 * 计算文件的MD5值
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 */
	 public static String getFileMD5(File file) throws FileNotFoundException {
         String value = null;
         FileInputStream in = new FileInputStream(file);
		 try {
		       MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
		       MessageDigest md5 = MessageDigest.getInstance("MD5");
		       md5.update(byteBuffer);
		       BigInteger bi = new BigInteger(1, md5.digest());
		       value = bi.toString(16);
		   } catch (Exception e) {
		       e.printStackTrace();
		   } finally {
		             if(null != in) {
		               try {
		             in.close();
		         } catch (IOException e) {
		             e.printStackTrace();
		         }
		       }
		   }
		   return value;
     }

	/**
	 * 计算上传文件流的MD5值
	 * @param is
	 * @param fileSize 文件大小
	 * @return
	 * @throws FileNotFoundException
	 */
	 public static String getFileMD5(InputStream is,Long fileSize) throws FileNotFoundException {
         String value = null;
         FileInputStream in =  (FileInputStream)is;
         
		 try {
		       MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0,fileSize);
		       MessageDigest md5 = MessageDigest.getInstance("MD5");
		       md5.update(byteBuffer);
		       BigInteger bi = new BigInteger(1, md5.digest());
		       value = bi.toString(16);
		   } catch (Exception e) {
		       e.printStackTrace();
		   } finally {
		             if(null != in) {
		               try {
		             in.close();
		         } catch (IOException e) {
		             e.printStackTrace();
		         }
		       }
		   }
		   return value;
     }
	 public static void main(String[] args) {
		try {
			System.out.println(getFileMD5(new File("d:\\货品导入模板-会员1.xlsx")));
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		}
	}
}
